package cn.wolfcode.myfilter;


import cn.wolfcode.domain.Result;
import cn.wolfcode.util.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//配置过滤器过滤的路径
@Slf4j
@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("Demo 拦截了 请求  执行放行逻辑");
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse resp=(HttpServletResponse) response;
        //获取请求路径
        /**
         * 除登录请求以外的请求
         */
        String requestURI=req.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        if(requestURI.equals("/login")){
            //如果是登录  直接放行  其他逻辑不再执行
            chain.doFilter(request,response);
            return;
        }
        String token=req.getHeader("token");
        //不是登录请求  解析JWT
        if(!StringUtils.isEmpty(token)){
            //Token 存在
            try {
                JwtUtils.parseJWT(token);
            } catch (Exception e) {
                log.info("JWT 解析失败");
                Result result=Result.error("NOT_LOGIN");
                //把Result 转换为JSON 字符串
                String json = JSONObject.toJSONString(result);
                resp.setContentType("application/json;charset=utf-8");
                resp.getWriter().write(json);
                e.printStackTrace();
            }
            //放行
            chain.doFilter(request,response);
        }else{
            log.info("JWT不存在");
            Result result=Result.error("NOT_LOGIN");
            //把 Result  转换为JSON 字符串
            String json=JSONObject.toJSONString(result);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(json);
            return;
        }


    }

    @Override
    public void destroy() {
        System.out.println("销毁方法");
        Filter.super.destroy();
    }
}
